// 用户中间件
const { REQUIRED, EXISTS, BIND, INCORRENT } = require("../config/error.js");
const { queryUserByName, verifyBind } = require("../server/userServer.js");
const md5password = require("../utils/md5handle.js");

// 验证用户 是否存在
const verifyUser = async (ctx, next) => {
	const { username, password } = ctx.request.body;
	// 用户名或密码是否为空
	if (!username || !password) {
		return ctx.app.emit("error", REQUIRED, ctx);
	}
	// 验证用户名是否已经被占用
	const result = await queryUserByName(username);
    // 如果result 有密码 说明是登录  检验密码是否正确
    if (result[0].password !== md5password(password)) {
        return ctx.app.emit("error", INCORRENT, ctx);
    } else {
        ctx.body = {
            code: 0,
            message: "用户名登录成功",
            data: result[0],
        };
    }
	await next();
};


// 注册时检验用户名是否被占用
const verifyExistUser = async (ctx ,next) => {
    const { username } = ctx.request.body;
    // 验证用户名是否已经被占用
	const result = await queryUserByName(username);
	if (!!result.length) {
        return ctx.app.emit("error", EXISTS, ctx);
    }
    await next();
}

// 加密密码 中间件
const hanlPassword = async (ctx, next) => {
	const { password } = ctx.request.body;
	ctx.request.body.password = md5password(password);
	await next();
};

// 验证此条用户信息是否绑定过
const verifyUserInfo = async (ctx, next) => {
	const { username, user_id } = ctx.request.body;
	const verify_name = Object.keys(ctx.request.body).filter(
		item => item === "username"
	)[0];
	const verify_data = verify_name && username;
	const res = await verifyBind(user_id, verify_name, verify_data);
	if (res) {
		return ctx.app.emit("error", BIND, ctx);
	}
	await next();
};

module.exports = { verifyUser, hanlPassword, verifyUserInfo , verifyExistUser };
